<?php

namespace App\Http\Livewire\Actions;

use App\Models\Archive;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use App\Models\Report as ReportModel;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Report extends Component
{
    use AuthorizesRequests;
    public $confirmingReport = false;

    public $content = '';

    public $archive;

    public function mount(Archive $archive)
    {
        $this->archive = $archive;
        $this->content = '';
    }

    public function confirmReport(ReportModel $report)
    {
        $this->resetErrorBag();

        $canCreate = Gate::inspect('create', [$report ,$this->archive]);
        if (!$canCreate->allowed()) {
            $this->emit('showMessage', [
                'title' => __('Failed.'),
                'type' => 'error',
                'content' => __('You have already reported.')
            ]);
        } else {
            $this->dispatchBrowserEvent('confirming-report');
            $this->confirmingReport = true;
        }
    }
    public function report(ReportModel $report)
    {
        $this->resetErrorBag();
        Validator::make([
            'content' => $this->content,
        ], [
            'content' => ['string', 'max:255'],
        ])->validateWithBag('content');
        if (!$this->canReport($report)) {
            // $this->dispatchBrowserEvent('confirming-report');
            $this->confirmingReport = false;
            return;
        }
        $report->content = $this->content;
        $report->archive_id = $this->archive->id;
        $report->user_id = Auth::id();
        $report->save();
        $this->emit('showMessage', [
            'title' => __('Success.'),
            'content' => __('Report Success.')
        ]);
        $this->confirmingReport = false;
    }

    private function canReport(ReportModel $report)
    {
        $canCreate = Gate::inspect('create', [$report ,$this->archive]);
        if (!$canCreate->allowed()) {
            $this->emit('showMessage', [
                'content' => __('You have already reported.'),
                'timeout' => 3000,
                'title' => __('Failed.'),
                'type' => 'error'
            ]);
            return false;
        }
        return true;
    }

    public function render()
    {
        return view('livewire.actions.report');
    }
}
